--[[
   @classmod Grid
]]

return Class {
   _name = "Grid",

   init = function (self, s, w, h)
      self.show = false
      self.sz = s or 8
      self.x, self.y = 0, 0
      self.selection = {}
      self.w, self.h = 128, 128
      self.show_coords = false
   end,
   
   reset = function (self)
      self.sz = 8
      self.x, self.y = 0, 0
      self.w, self.h = 128, 128
   end,
   
   snap = function (self, x, y)
      return math.floor(x/self.sz)*self.sz, y and math.floor(y/self.sz)*self.sz
   end,
   
   highlight = function (self, x, y, c)
      self.selection_color = c or {1, 1, 1}
      local tx, ty = self:snap(x, y)
      self.tx, self.ty = tx, ty
   end,
   
   get_highlighted_tile_pos = function (self)
      return self.tx, self.ty
   end,
   
   update = function (self)
      if Game.current_tile then
	 self.tx, self.ty = Game.current_tile:get_position ()
      else
	 self.tx, self.ty = nil, nil
      end
   end,
   
   draw_coordinates = function (self)
      if not self.show_coords then return end
      local tx, ty = self.tx, self.ty
      local w, h = self.w, self.h
      _lg.setLineWidth(1)
      _lg.setColor(.1, .1, .1, 1)
      _lg.line(tx, self.x, tx, ty)
      _lg.line(tx, ty, self.x, ty)
      
   end,
   
   resize = function (self, w, h)
      self.w, self.h = w, h
   end,
   
   move = function (self, x, y)
      self.x, self.y = x, y
   end,
   
   draw = function (self)
      if self.show then
	 local w, h = self.w, self.h
	 love.graphics.setColor(.2, .2, .2, .5)
	 for y = self.y, self.y + h, self.sz do
	    love.graphics.line(self.x, y, self.x + w, y)
	 end
	 for x = self.x, self.x + w, self.sz do
	    love.graphics.line(x, self.y, x, self.y + h)
	 end
      end
      if self.tx and self.ty then 
	 love.graphics.rectangle('line', self.tx, self.ty, 8, 8)
      end
   end
}
